# encoding: utf-8
"""
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    created by lei.chang on '18/12/2024'
    comment: 文档切分
"""
import ujson
from fastapi import UploadFile
import aiohttp
from aiohttp.formdata import FormData

from project.core.exception import BizError
from project.lib.common import logger


class FileToText:
    """ 文件提取文本
    """
    url = 'http://47.106.100.132:18000/convert'
    user_name = '_username_Pfa_45rfregw#'
    user_password = '_password_@@#$WuDV^fds'

    @classmethod
    async def convert(cls, file: UploadFile):
        """ 提取文本
        :return:
        """
        content_streaming = await file.read()
        file_name = file.filename

        form = FormData()
        form.add_field('file', content_streaming, filename=file_name, content_type='application/octet-stream')
        auth = aiohttp.BasicAuth(login=cls.user_name, password=cls.user_password)

        async with aiohttp.ClientSession(auth=auth) as session:
            async with session.post(cls.url, data=form) as resp:
                if resp.status != 200:
                    raise BizError(f'文档提取文本失败 status: {resp.status} url: {cls.url}')

                result = await resp.json()
                if result.get('result') != 'success':
                    logger.critical(f'{result.get("messages", "")}, url: {cls.url}')
                    raise BizError(code=result.get('code'), message=result.get("messages", ""))

            return result
